package com.vajava.str;

import org.junit.After;
import org.junit.Before;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;

public abstract class FunctionalTestCase {
    protected EntityManager em;
    protected EntityTransaction transaction;

    @Before
    public void setUp() throws Exception {
        Map configOverrides = new HashMap();
        configOverrides.put("hibernate.hbm2ddl.auto", "create-drop");
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("strManager", configOverrides);
        em = emf.createEntityManager();
    }

    protected EntityTransaction beginTransaction() {
        if (transaction != null && transaction.isActive()) {
            throw new IllegalStateException("Cannot start a new transaction until previous one is closed");
        }
        transaction = em.getTransaction();
        transaction.begin();
        return transaction;
    }

    @After
    public void tearDown() throws Exception {
        if (transaction != null) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
        }
        if (em != null) {
            if (em.isOpen()) {
                em.close();
            }

        }
    }
}
